<template xmlns:v-action="">
    <a-card :bordered="false">
        <div class="table-page-search-wrapper">
            <a-form layout="inline" ref="queryPermissionForm" :form="queryPermissionForm">

                <a-row :gutter="48">
                    <a-col :md="8" :sm="24">
                        <a-form-item label="权限名称">
                            <a-input v-decorator="['permissionName',{ rules: [{ required: false}] }]"/>
                        </a-form-item>
                    </a-col>
                    <template v-if="advanced">
                    <a-col :md="8" :sm="24">
                        <a-form-item label="权限值">
                            <a-input v-decorator="['permissionValue',{ rules: [{ required: false}] }]"/>
                        </a-form-item>
                    </a-col>
                    <a-col :md="8" :sm="24">
                        <a-form-item label="权限类型：">
                            <a-select placeholder="请选择" v-decorator="['type',{ rules: [{ required: false}] }]">
                                <a-select-option value="">请选择</a-select-option>
                                <a-select-option value="0">目录</a-select-option>
                                <a-select-option value="1">菜单</a-select-option>
                                <a-select-option value="2">按钮</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :md="8" :sm="24">
                        <a-form-item label="状态">
                            <a-select placeholder="请选择" v-decorator="['status',{ rules: [{ required: false}] }]">
                                <a-select-option value="">请选择</a-select-option>
                                <a-select-option value="0">关闭</a-select-option>
                                <a-select-option value="1">启用</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    </template>
                    <a-col :md="!advanced && 8 || 24" :sm="24">
                    <span class="table-page-search-submitButtons" :style="advanced && { float: 'right', overflow: 'hidden' } || {} ">
                        <a-button type="primary" @click="handleSearchPermission">查询</a-button>
                        <a-button style="margin-left: 8px" @click="handleSearchResetPermission">重置</a-button>
                        <a @click="toggleAdvanced" style="margin-left: 8px">
                            {{ advanced ? '收起' : '展开' }}
                            <a-icon :type="advanced ? 'up' : 'down'"/>
                        </a>
                    </span>
                    </a-col>
                </a-row>
            </a-form>
        </div>

        <div class="table-operator">
            <a-button type="primary" v-action:ums_permission_add icon="plus" @click="handleAddPermission">新建</a-button>
            <a-dropdown v-if="selectedRowKeys.length > 0">
                <a-menu slot="overlay">
                    <a-menu-item key="1" v-action:ums_permission_delete @click="handleBatchDeletePermission"><a-icon type="delete" />删除</a-menu-item>
                    <!-- lock | unlock -->
                    <a-menu-item key="2"><a-icon type="lock" />扩展</a-menu-item>
                </a-menu>
                <a-button style="margin-left: 8px">
                    批量操作 <a-icon type="down" />
                </a-button>
            </a-dropdown>
        </div>

        <!-- 列表  -->
        <s-table
                ref="table"
                size="default"
                :pageSize="100"
                rowKey="permissionId"
                :columns="columns"
                :data="loadData"
                :alert="{ show: true, clear: true }"
                :rowSelection="{ selectedRowKeys: this.selectedRowKeys, onChange: this.onSelectChange }"
        >
            <template v-for="(col, index) in columns" v-if="col.scopedSlots" :slot="col.dataIndex" slot-scope="text">
                <div :key="index">
                    <template>{{ text }}</template>
                </div>
            </template>
            <template slot="status" slot-scope="text">
                <div v-if="text==1">启用</div>
                <div v-if="text==0">关闭</div>
            </template>
            <template slot="icon" slot-scope="text">
                <a-icon :type="text" v-if="text" /> {{text}}
            </template>
            <template slot="permissionType" slot-scope="permissionType">
                <div v-if="permissionType==0">目录</div>
                <div v-if="permissionType==1">菜单</div>
                <div v-if="permissionType==2">按钮</div>
            </template>
            <span slot="action" slot-scope="text, record">
                <a @click="handleEditPermission(record)">编辑</a>
                <a-divider type="vertical" />
                <a-dropdown>
                    <a class="ant-dropdown-link">
                        更多 <a-icon type="down" />
                    </a>
                    <a-menu slot="overlay">
                        <a-menu-item>
                            <a href="javascript:" @click="handleDetailPermission(record)" >详情</a>
                        </a-menu-item>
                        <a-menu-item>
                            <a href="javascript:" v-if="record.status===1" @click="handleDisableStatusPermission(record)">关闭</a>
                            <a href="javascript:" v-if="record.status===0" @click="handleDisableStatusPermission(record)">启用</a>
                        </a-menu-item>
                        <a-menu-item v-if="record.type===1" >
                            <a href="javascript:" @click="handleButtonPermission(record)">按钮</a>
                        </a-menu-item>
                        <a-menu-item>
                            <a href="javascript:" @click="handleDeletePermission(record)">删除</a>
                        </a-menu-item>
                    </a-menu>
                </a-dropdown>
            </span>
        </s-table>
        <!--   新建表单 -->
        <a-modal
                title="新建"
                :width="800"
                v-model="addModelVisible"
                :confirmLoading="addConfirmLoading"
                @ok="handleSavePermission"
        >
            <a-form :form="addPermissionForm">
                        <a-form-item
                                :labelCol="labelCol"
                                :wrapperCol="wrapperCol"
                                label="父级权限"
                                hasFeedback >
                            <a-tree-select
                                show-search
                                treeNodeFilterProp="title"
                                style="width: 100%"
                                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                                :tree-data="permissionTreeData"
                                placeholder="Please select"
                                v-decorator="[ 'parentId',{ rules: [{ required: false, message: '父级权限' }] }]"
                            >
                            </a-tree-select>
                        </a-form-item>
                        <a-form-item
                                :labelCol="labelCol"
                                :wrapperCol="wrapperCol"
                                label="权限名称"
                                hasFeedback >
                            <a-input v-decorator="[ 'permissionName',{ rules: [{ required: false, message: '权限名称' }] }]"/>
                        </a-form-item>
                        <a-form-item
                                :labelCol="labelCol"
                                :wrapperCol="wrapperCol"
                                label="权限值"
                                hasFeedback >
                            <a-input v-decorator="[ 'permissionValue',{ rules: [{ required: false, message: '权限值' }] }]"/>
                        </a-form-item>
                        <a-form-item
                                :labelCol="labelCol"
                                :wrapperCol="wrapperCol"
                                label="后台权限"
                                hasFeedback >
                            <a-input v-decorator="[ 'authority',{ rules: [{ required: false, message: '后台权限' }] }]"/>
                        </a-form-item>
                        <a-form-item
                                :labelCol="labelCol"
                                :wrapperCol="wrapperCol"
                                label="图标"
                                hasFeedback >
                            <a-input v-decorator="[ 'icon',{ rules: [{ required: false, message: '图标' }] }]"/>
                        </a-form-item>
                        <a-form-item
                                :labelCol="labelCol"
                                :wrapperCol="wrapperCol"
                                label="权限类型"
                                hasFeedback >
                            <a-select placeholder="请选择" v-decorator="['type',{ rules: [{ required: false}] }]">
                                <a-select-option value="">请选择</a-select-option>
                                <a-select-option value="0">目录</a-select-option>
                                <a-select-option value="1">菜单</a-select-option>
                                <a-select-option value="2">按钮</a-select-option>
                            </a-select>
                        </a-form-item>
                        <a-form-item
                                :labelCol="labelCol"
                                :wrapperCol="wrapperCol"
                                label="排序"
                                hasFeedback >
                            <a-input v-decorator="[ 'sort',{ rules: [{ required: false, message: '排序' }] }]"/>
                        </a-form-item>
                        <a-form-item
                                :labelCol="labelCol"
                                :wrapperCol="wrapperCol"
                                label="状态"
                        >
                            <a-select
                                    v-decorator="['status',{ rules: [{ required: false, message: '请选择状态!' }] }]"
                                    placeholder="请选择状态"
                            >
                                <a-select-option :value="1">启用</a-select-option>
                                <a-select-option :value="0">关闭</a-select-option>
                            </a-select>
                        </a-form-item>
                <a-divider />
            </a-form>
        </a-modal>
        <!--   编辑表单 -->
        <a-modal
                title="编辑"
                :width="800"
                v-model="editModelVisible"
                :confirmLoading="editConfirmLoading"
                @ok="handleUpdatePermission"
        >
            <a-form :form="editPermissionForm">
                <a-form-item
                        :labelCol="labelCol"
                        :wrapperCol="wrapperCol"
                        label="权限名称"
                        hasFeedback >
                    <a-input v-decorator="[ 'permissionName',{ rules: [{ required: false, message: '权限名称' }] }]" />
                </a-form-item>
                <a-form-item
                        :labelCol="labelCol"
                        :wrapperCol="wrapperCol"
                        label="权限值"
                        hasFeedback >
                    <a-input v-decorator="[ 'permissionValue',{ rules: [{ required: false, message: '权限值' }] }]" />
                </a-form-item>
                <a-form-item
                        :labelCol="labelCol"
                        :wrapperCol="wrapperCol"
                        label="后台权限"
                        hasFeedback >
                    <a-input v-decorator="[ 'authority',{ rules: [{ required: false, message: '后台权限' }] }]" />
                </a-form-item>
                <a-form-item
                        :labelCol="labelCol"
                        :wrapperCol="wrapperCol"
                        label="图标"
                        hasFeedback >
                    <a-input v-decorator="[ 'icon',{ rules: [{ required: false, message: '图标' }] }]" />
                </a-form-item>
                <a-form-item
                        :labelCol="labelCol"
                        :wrapperCol="wrapperCol"
                        label="排序"
                        hasFeedback >
                    <a-input v-decorator="[ 'sort',{ rules: [{ required: false, message: '排序' }] }]" />
                </a-form-item>
                <a-form-item
                        :labelCol="labelCol"
                        :wrapperCol="wrapperCol"
                        label="状态"
                >
                    <a-select
                            v-decorator="['status',{ rules: [{ required: false, message: '请选择状态!' }] }]"
                            placeholder="请选择状态"
                    >
                        <a-select-option :value="1">启用</a-select-option>
                        <a-select-option :value="0">关闭</a-select-option>
                    </a-select>
                </a-form-item>
                <a-divider />
            </a-form>
        </a-modal>
        <a-modal
            title="权限设置"
            :width="800"
            v-model="buttonModelVisible"
            :confirmLoading="buttonConfirmLoading"
            @ok="handleUpdateButtonPermission"
        >
            <a-form>
                <a-form-item
                        :labelCol="labelCol"
                        :wrapperCol="wrapperCol"
                        label="菜单名称">
                        <label>{{editPermissionRecord.permissionName}}</label>
                </a-form-item>
                <a-form-item
                        :labelCol="labelCol"
                        :wrapperCol="wrapperCol"
                        label="操作权限">
                        <a-row>
                            <a-checkbox :indeterminate="buttonsIndeterminate" :checked="buttonsCheckAll" @change="onButtonsPermissionCheckAllChange">
                                全选
                            </a-checkbox>
                            <a-checkbox-group v-model="buttonsCheckedList" :options="plainOptions" @change="onButtonPermissionChange" />
                        </a-row>
                </a-form-item>
            </a-form>
        </a-modal>
    </a-card>
</template>

<script>
    import { STable } from '@/components'
    import api from '@/api'
    import { deletePermission, updatePermission, addPermission, batchDeletePermission, updateOperatePermission } from '@/api/permissionApi'

    export default {
        name: 'PermissionList',
        data () {
        return {
            description: '',
            labelCol: {
                xs: { span: 24 },
                sm: { span: 5 }
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 16 }
            },
            queryPermissionForm: this.$form.createForm(this, { name: 'query_form' }),
            addModelVisible: false,
            addConfirmLoading: false,
            addPermissionForm: this.$form.createForm(this, { name: 'add_form' }),
            editPermissionForm: this.$form.createForm(this, { name: 'edit_form' }),
            editPermissionRecord: {},
            editModelVisible: false,
            editConfirmLoading: false,
            buttonModelVisible: false,
            buttonConfirmLoading: false,
            // 高级搜索 展开/关闭
            advanced: false,
            // 查询参数
            queryParam: {
            },
            // 表头

            columns: [
                {
                    title: '权限名称',
                    dataIndex: 'permissionName',
                    // width: '100',
                    sorter: false,
                    // scopedSlots: { customRender: '' },
                    needTotal: false
                },
                {
                    title: '权限值',
                    dataIndex: 'permissionValue',
                    // width: '100',
                    sorter: false,
                    // scopedSlots: { customRender: '' },
                    needTotal: false
                },
                {
                    title: '后台权限',
                    dataIndex: 'authority',
                    // width: '100',
                    sorter: false,
                    // scopedSlots: { customRender: '' },
                    needTotal: false
                },
                {
                    title: '图标',
                    dataIndex: 'icon',
                    // width: '100',
                    sorter: false,
                    scopedSlots: { customRender: 'icon' },
                    needTotal: false
                },
                {
                    title: '权限类型',
                    dataIndex: 'type',
                    // width: '100',
                    sorter: false,
                    scopedSlots: { customRender: 'permissionType' },
                    needTotal: false
                },
                {
                    title: '状态',
                    dataIndex: 'status',
                    // width: '100',
                    sorter: false,
                    scopedSlots: { customRender: 'status' },
                    // scopedSlots: { customRender: '' },
                    needTotal: false
                },
                {
                    table: '操作',
                    dataIndex: 'action',
                    width: '150',
                    scopedSlots: { customRender: 'action' }
                }
            ],
            // 加载数据方法 必须为 Promise 对象
            loadData: parameter => {
                return this.$http.get(api.permissionTreeUrl, {
                    params: Object.assign(parameter, this.queryParam)
                }).then(res => {
                    return res.data
                }, err => {
                    this.$notification['error']({
                        message: '提示',
                        description: err.msg || '加载数据失败',
                        duration: 8
                    })
                    return { pageNo: 0, totalCount: 0, data: [] }
                })
            },
            selectedRowKeys: [],
            selectedRows: [],
            permissionTreeData: [],
            replaceFields: { children: 'children', title: 'permissionName', key: 'permissionId', value: 'permissionId' },
            plainOptions: [
                { value: 'query', label: '查询' },
                { value: 'add', label: '新增' },
                { value: 'edit', label: '修改' },
                { value: 'delete', label: '删除' },
                { value: 'detail', label: '详情' },
                { value: 'import', label: '导入' },
                { value: 'export', label: '导出' }
                ],
            buttonsIndeterminate: false,
            buttonsCheckAll: false,
            buttonsCheckedList: []
        }
        },
        components: {
            STable
        },
        methods: {
            // 按钮权限 选择事件
            onButtonPermissionChange(checkedList) {
                this.buttonsIndeterminate = !!checkedList.length && checkedList.length < this.plainOptions.length;
                this.buttonsCheckAll = checkedList.length === this.plainOptions.length;
            },
            // 按钮权限 全选按钮事件
            onButtonsPermissionCheckAllChange(e) {
                let allOptions = []
                this.plainOptions.forEach(item => {
                    allOptions.push(item.value)
                })
                this.buttonsCheckedList = e.target.checked ? allOptions : []
                this.buttonsIndeterminate = false
                this.buttonsCheckAll = e.target.checked
            },
            // 搜索查询
            handleSearchPermission () {
                this.queryParam = this.queryPermissionForm.getFieldsValue()
                this.loadData = parameter => {
                    return this.$http.get(api.permissionTreeUrl, {
                    params: Object.assign(parameter, this.queryParam)
                    }).then(res => {
                        return res.data
                    })
                }
                this.$refs.table.refresh()
            },
            // 加载权限树选中器
            loadPermissionTreeData() {
                if(!this.permissionTreeData || this.permissionTreeData.length === 0) {
                    this.$http.get(api.getPermissionSelectTreeUrl)
                    .then(res => {
                        this.permissionTreeData = res.data
                    })
                }
            },
             // 搜索重置
            handleSearchResetPermission () {
                this.queryPermissionForm.resetFields()
            },
            handleChangePermission (value, key, column, record) {
                record[column.dataIndex] = value
            },
            handleEditPermission (record) {
                this.editPermissionRecord = Object.assign({}, record)
                this.editModelVisible = true
                this.$nextTick(() => {
                    let values = this.editPermissionForm.getFieldsValue()
                    for(let key in values) {
                        values[key] = this.editPermissionRecord[key];
                        this.editPermissionForm.setFieldsValue(values)
                    }
                })
            },
            // 新增
            handleAddPermission () {
                this.addPermissionRecord = {}
                this.addModelVisible = true
                this.addPermissionForm.resetFields();
                this.loadPermissionTreeData();
            },
             // 批量删除
            handleBatchDeletePermission () {
                let ids = this.selectedRowKeys
                let params = this.selectedRowKeys
                const that = this
                this.$confirm({
                    title: '警告',
                    content: `真的要批量删除 ${ids.length} 个吗?`,
                    okText: '删除',
                    okType: 'danger',
                    cancelText: '取消',
                    onOk () {
                        // 在这里调用删除接口
                        return new Promise((resolve, reject) => {
                            batchDeletePermission(params)
                            .then(res => {
                                that.$refs.table.clearSelected()
                                        that.$refs.table.refresh()
                                        that.$notification['success']({
                                            message: '提示',
                                            description: res.msg || '删除成功',
                                            duration: 8
                                        })
                                resolve()
                            }).catch((err) => {
                            reject(err)
                            that.$notification['error']({
                                message: '提示',
                                description: err.msg || '删除失败',
                                duration: 8
                            })
                        })
                    }).catch(() => console.log('Oops errors!'))
                    },
                    onCancel () {
                    }
                })
            },
            edit (row) {
                row.editable = true
            },
            handleDeletePermission (row) {
                const that = this
                this.$confirm({
                    title: '警告',
                    content: `真的要删除吗?`,
                    okText: '删除',
                    okType: 'danger',
                    cancelText: '取消',
                    onOk () {
                        // 在这里调用删除接口
                        return new Promise((resolve, reject) => {
                            deletePermission(row.permissionId)
                    .then(res => {
                            that.$refs.table.refresh()
                                    that.$notification['success']({
                                        message: '提示',
                                        description: res.msg || '删除成功',
                                        duration: 8
                                    })
                            resolve()
                        }).catch((err) => {
                            reject(err)
                            that.$notification['error']({
                                message: '提示',
                                description: err.msg || '删除失败',
                                duration: 8
                            })
                        })
                    }).catch(() => console.log('Oops errors!'))
                    },
                    onCancel () {
                    }
                })
            },
            handleDetailPermission (row) {
            },
            // 更多>>按钮 事件
            handleButtonPermission (row) {
                this.editPermissionRecord = row;
                this.buttonModelVisible = true;
                // 加载按钮权限
                let param = {
                    'parentId': row.permissionId,
                    'pageSize': 100
                }
                this.$http.get(api.permissionUrl, {
                    params: param
                }).then(res => {
                    let data = res.data.data
                    this.buttonsCheckedList = []
                    if(data && data.length > 0) {
                        data.forEach(item => {
                            this.buttonsCheckedList.push(item.permissionValue)
                        })
                    }
                    this.onButtonPermissionChange(this.buttonsCheckedList)
                }, err => {
                    this.$notification['error']({
                        message: '提示',
                        description: err.msg || '加载按钮权限数据失败',
                        duration: 8
                    })
                })
            },
            handleDisableStatusPermission (row) {
                const that = this
                let txt = row.status === 1 ? '关闭' : '启用'
                this.$confirm({
                    title: '警告',
                    content: `真的要${txt}吗?`,
                    okText: txt,
                    okType: 'danger',
                    cancelText: '取消',
                    onOk () {
                        // 在这里调用更新接口
                        return new Promise((resolve, reject) => {
                            let params = { 'permissionId': row.permissionId,
                                'status': row.status === 1 ? 0 : 1 }
                            updatePermission(row.permissionId, params)
                    .then(res => {
                            that.$refs.table.refresh()
                                    that.$notification['success']({
                                        message: '提示',
                                        description: res.msg || '操作成功',
                                        duration: 8
                                    })
                            resolve()
                        }).catch((err) => {
                            reject(err)
                            that.$notification['error']({
                                message: '提示',
                                description: err.msg || '操作失败',
                                duration: 8
                            })
                        })
                    }).catch(() => console.log('Oops errors!'))
                    },
                    onCancel () {
                    }
                })
            },
            // 保存
            handleSavePermission () {
                this.addPermissionForm.validateFields((err, values) => {
                    if (err) {
                        return;
                    }
                    this.addRecord = values
                    this.addConfirmLoading = true;
                    // 新增操作
                    addPermission(this.addRecord)
                    .then(res => {
                        this.$notification['success']({
                            message: '提示',
                            description: res.msg || '操作成功',
                            duration: 8
                        })
                        this.addPermissionForm.resetFields();
                        this.addModelVisible = false;
                        this.addConfirmLoading = false;
                        this.$refs.table.refresh()
                    })
                    .catch((err) => {
                        this.addConfirmLoading = false;
                        this.$notification['error']({
                            message: '提示',
                            description: err.msg || '操作失败',
                            duration: 8
                        })
                    });
                });
            },
            // 更新
            handleUpdatePermission () {
                this.editPermissionForm.validateFields((err, values) => {
                    if (err) {
                        return;
                    }
                    let updateId = this.editPermissionRecord.permissionId
                    this.editPermissionRecord = values
                    this.editConfirmLoading = true;
                    // 更新操作
                    updatePermission(updateId, values)
                            .then(res => {
                                this.$notification['success']({
                                    message: '提示',
                                    description: res.msg || '操作成功',
                                    duration: 8
                                })
                                this.editPermissionForm.resetFields();
                                this.editModelVisible = false;
                                this.editConfirmLoading = false;
                                this.$refs.table.refresh()
                            })
                    .catch((err) => {
                            this.editConfirmLoading = false;
                        this.$notification['error']({
                            message: '提示',
                            description: err.msg || '操作失败',
                            duration: 8
                        })
                    });
                });
            },
            // 更新按钮权限
            handleUpdateButtonPermission () {
                let permissionId = this.editPermissionRecord.permissionId
                let params = { permissionId, operators: this.buttonsCheckedList }
                this.buttonConfirmLoading = true;
                // 更新操作
                updateOperatePermission(params)
                    .then(res => {
                        this.$notification['success']({
                            message: '提示',
                            description: res.msg || '操作成功',
                            duration: 8
                        })
                        this.editPermissionRecord = {};
                        this.buttonModelVisible = false;
                        this.buttonConfirmLoading = false;
                        this.$refs.table.refresh()
                    })
                .catch((err) => {
                    this.buttonConfirmLoading = false;
                    this.$notification['error']({
                        message: '提示',
                        description: err.msg || '操作失败',
                        duration: 8
                    })
                });
            },
            onSelectChange (selectedRowKeys, selectedRows) {
                this.selectedRowKeys = selectedRowKeys
                this.selectedRows = selectedRows
            },
            toggleAdvanced () {
                this.advanced = !this.advanced
            }
        }
    }
</script>

<style lang="less" scoped>
    .search {
        margin-bottom: 54px;
    }

    .fold {
        width: calc(100% - 216px);
        display: inline-block
    }

    .operator {
        margin-bottom: 18px;
    }

    @media screen and (max-width: 900px) {
        .fold {
            width: 100%;
        }
    }
</style>
